// React基础组件
import React from 'react'
// dva 连接组件 - 连接route和model
import { connect } from 'dva'
// 引入antd的组件
import { Form,Radio, Button,Table,Popconfirm, Modal, Row, Col, Input, Select, Cascader, Icon, Checkbox, Tabs, DatePicker, message } from 'antd'
//导入路由组件，用于跳转等
import { Link, hashHistory } from 'dva/router'
// 导入项目全局配置文件
import config from 'config/config'
// 引入model取值工具方法
import { mapStateToProps } from 'utils/view_utils'
// 当前组件样式
import styles from './kernelGoodsDetailStyle.less'
import { CollapsiblePanels } from 'widget/CollapsiblePanels/index'
import { Grid } from 'widget/Grid/index'
import moment from 'moment';

const FormItem = Form.Item
const { RangePicker,MonthPicker } = DatePicker
const { Option } = Select;
const { TextArea } = Input;
const confirm = Modal.confirm;
/**
 * description 路由视图及事件处理
 * dispatch 分发到models中的effects对应事件名
 * model 用于获取models中state定义的数据
 * form 表单对象
 */
const kernelGoodsDetailView = function ({ dispatch, model, form }) {
  // 表单的子函数
  const { resetFields, getFieldDecorator, validateFields, setFieldsValue,validateFieldsAndScroll  } = form
  // 取出model对象，命名空间
  const { modelObj, namespace } = model
  let {distributionNameList, visible,count,query, actionType, btnLoading } = modelObj

  const formItemLayoutPro = {
    labelCol: { span: 6 },
    wrapperCol: { span: 14 },
  };

  const columns = [
    {
      key: "ruleNo",
      title: "编号",
      width: 80,
      render: (a, item, index, d, e, f) => {
        return index+1
      },
    },
    {
      title: '区域', dataIndex: 'area', key: 'area', width: 200,
      render: function (value, item, index) {
        return item.area
      }
    },
    {
      title: '我司项目',dataIndex: 'productName',key: 'productName',width: 200,
      render: function (value, item, index) {
        return item.productName
      }
    },
    {
        title: () => (
          <span>
            {'我司主推业态'}
            <span style={{color: 'red'}}>*</span>
          </span>
        ), dataIndex: 'companyType', key: 'companyType',width:200,
        render: function (value, item, index) {
            return (<div key={index}>
                    <FormItem style={{marginBottom: 0,zIndex:0,marginRight: '16px'}}>
                      {getFieldDecorator(`companyType_${index}`, {
                          rules: [{
                            required: true,whitespace: true, message: '请选择我司主推业态'
                          }],
                          initialValue: item.companyType,
                      })(
                        <Select allowClear={true} disabled={actionType == 'check'} placeholder="请选择" onChange={(e)=>{tableChange(e,'companyType',item)}}>
                            <Select.Option value="高层">高层</Select.Option>
                            <Select.Option value="洋房">洋房</Select.Option>
                            <Select.Option value="叠墅">叠墅</Select.Option>
                            <Select.Option value="别墅">别墅</Select.Option>
                        </Select>
                      )}
                  </FormItem>
                </div>)
        }
    },
    {
        title:   () => (
          <span>
            {'我司项目成交均价(元/m²)'}
            <span style={{color: 'red'}}>*</span>
          </span>
        ) ,dataIndex: 'companyAverage',key: 'companyAverage',width: 200,
        render: function (value, item, index) {
          return (<div key={index}>
            <FormItem style={{marginBottom: 0}}>
            {getFieldDecorator(`companyAverage_${index}`, {
                rules: [{
                  required: true, message: '数据未关联，请重选我司主推业态'
                }],
                initialValue: item.companyAverage,
            })(
              <Input disabled={true} 
                onChange={(e) => { tableChange(e.target.value, 'companyAverage',item) }}
                />
            )}
          </FormItem>
        </div>)
        }
    },
    {
        title:  () => (
          <span>
            {'我司项目成交金额(万元)'}
            <span style={{color: 'red'}}>*</span>
          </span>
        ) ,dataIndex: 'companyAmount',key: 'companyAmount',width: 200,
        render: function (value, item, index) {
            return (<div key={index}>
              <FormItem style={{marginBottom: 0}}>
              {getFieldDecorator(`companyAmount_${index}`, {
                  rules: [{
                    required: true, message: '数据未关联，请重选我司主推业态'
                  }],
                  initialValue: item.companyAmount,
              })(
                <Input disabled={true} 
                  onChange={(e) => { tableChange(e.target.value, 'companyAmount',item) }}
                  />
              )}
            </FormItem>
          </div>)
        }
    },
    {
        title: () => (
          <span>
            {'核心竞品'}
            <span style={{color: 'red'}}>*</span>
          </span>
        ), dataIndex: 'competName', key: 'competName',width:200,
        render: function (value, item, index) {
            return <div onClick={() => { tableClick(value,item,index) }}>
                <FormItem style={{marginBottom: 0}}>
                      {getFieldDecorator(`competName_${index}`, {
                          rules: [{
                            required: true,whitespace: true, message: '请选择核心竞品'
                          }],
                          initialValue: item.competName,
                      })(
                        <Select allowClear={true} disabled={actionType == 'check'} placeholder="请选择" onChange={(e)=>{tableChange(e,'competId',item)}}>
                              { distributionNameList == undefined ?null:distributionNameList.map((itemed,key)=>{
                                return <Select.Option value={itemed.competId} key={key}>{itemed.competName}</Select.Option>
                              })}
                        </Select>
                      )}
                  </FormItem>
            </div>
        }
    },
    {
      title: '核心竞品业态', dataIndex: 'competType', key: 'competType',width: 180,
      render: function (value, item, index) {
        return <div>
        <Input value = {item.competType}  disabled={true}
            onChange={(e) => { tableChange(e.target.value, 'competType',item) }}
          />
      </div>
      }
    }, 
    {
      title: () => (
        <span>
          {'核心竞品成交均价(元/m²)'}
          <span style={{color: 'red'}}>*</span>
        </span>
      ), dataIndex: 'competAverage', key: 'competAverage',width: 200,
      render: function (value, item, index) {
        return <div  key={index}>
         <FormItem style={{marginBottom: 0}}>
            {getFieldDecorator(`competAverage_${index}`, {
                rules: [{
                  required: true, message: '请输入均价'
                },{ pattern: /^[+-]?\d*\.?\d*$/, message: '请输入数字' }],
                initialValue: item.competAverage,
            })(
              <Input disabled={actionType == 'check'} 
                onChange={(e) => { tableChange(e.target.value, 'competAverage',item) }}
                />
            )}
          </FormItem>
      </div>
      }
    }, 
    {
      title:  () => (
        <span>
          {'核心竞品成交金额(万元)'}
          <span style={{color: 'red'}}>*</span>
        </span>
      ), dataIndex: 'competAmount', key: 'competAmount',width: 200,
      render: function (value, item, index) {
      return (<div key={index}>
            <FormItem style={{marginBottom: 0}}>
            {getFieldDecorator(`competAmount_${index}`, {
                rules: [{
                  required: true, message: '请输入均价'
                },{ pattern: /^[+-]?\d*\.?\d*$/, message: '请输入数字' }],
                initialValue: item.competAmount,
            })(
              <Input disabled={actionType == 'check'} 
                onChange={(e) => { tableChange(e.target.value, 'competAmount',item) }}
                />
            )}
          </FormItem>
        </div>)
      }
    },
    {
        title: '操作',
        dataIndex: 'operation',
        width: 100,
        render: function (value, item, index) {
            return <div>
                {/* {item.id&&actionType != 'edit'&&<span onClick={() => addContent(item.id)} style={{color:'#0877fd',cursor: 'pointer'}}>添加</span>} */}
                {actionType != 'edit'&&<span onClick={() => deledeFun(item.id)} style={{color:'red',cursor: 'pointer'}}>删除</span>}
          </div>
        }
    },
  ]
 
  //输入框改变时
  function inputChange(value, name) {
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {
        query: {
          ...query,
          [name]: value,
        }
      }
    })
    form.resetFields()
  }

  //表格改变时
  function tableChange (value, name,item) {
    let tempId = item.id?item.id:item.key
    let obj = {[name]: value}
    for(var itt of query.Corecompet){
        if(itt.id== tempId){
          itt = Object.assign(itt, obj)
        }
        if(itt.key== tempId){
          itt = Object.assign(itt, obj)
        }
    }
    dispatch({
      type: `${namespace}/updateStore`,
      payload: {query}
    })
    if(name == 'companyType'){
      for(var pt of query.Corecompet){
        if(pt.id== tempId){
          pt.competType = value
        }
        if(pt.key== tempId){
          pt.competType = value
        }
      }
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {query}
      })
      dispatch({
        type: `${namespace}/queryByRg`,
        payload: {item,value,tempId}
      })
    }
    if(name == 'competId'){
      let competName = ''
      for(var pp of distributionNameList){
        if(pp.competId== value){
          competName = pp.competName
        }
      }
      for(var ty of query.Corecompet){
        if(ty.competId== value){
          ty.competName = competName
        }
      }
      dispatch({
        type: `${namespace}/updateStore`,
        payload: {query}
      })
    }
    form.resetFields()
  }
  function tableClick(value,item,index){
     dispatch({
        type: `${namespace}/getProjectByCompet`,
        payload: {item}
      })
  }
  function submit(){
    validateFieldsAndScroll((err) => {
      if (err) {
        return false
      } else {
        dispatch({
          type: `${namespace}/submit`,
          payload: {}
        })
      }
    })
  }
  // function addContent(id){
  //   let tempList = JSON.parse(JSON.stringify(query.Corecompet))
  //   let obj ={}
  //   if(tempList.length){
  //     for(let i=0;i<tempList.length;i++){
  //       if(tempList[i].id == id){
  //         obj = tempList[i]
  //         obj.key = count+1
  //         delete obj.id
  //         query.Corecompet.push(obj)        }
  //     }
  //   }
  //   count = count+1
  //   dispatch({
  //     type: `${namespace}/updateStore`,
  //     payload: {query,count}
  //   })
  // }
  function deledeFun(id){
    confirm({
      title: '删除确认',
      content: '您确认删除所选的数据吗？',
      okText: '确认',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        query.Corecompet = query.Corecompet.filter(item => item.id != id)
        dispatch({
          type: `${namespace}/updateStore`,
          payload: {query}
        })
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  function updateCancel(){
    visible = !visible
    dispatch({
      type: `${namespace}/updateStore`,
      payload: { visible }
    })
  }

  return (
    <div className='public_listMain'>
      <div className={"functionButton"}>
        <Button disabled={actionType == 'check'} type='primary' onClick={e => submit()} loading={btnLoading}>保存</Button>
      </div>

      <CollapsiblePanels title="核心竞品数据录入" hideUpDownBtn={true} >
      <Row style={{position:'relative'}}>
          <Col span={8}>
            <FormItem label='统计月份'  {...formItemLayoutPro}>
              {getFieldDecorator('month', {
                rules: [{
                  required: true, message: '注：所选月份已存在数据，请重新选择月份'
                }],
                initialValue: query.month ? moment(query.month, 'YYYY-MM-DD') : null
              })(
                <MonthPicker disabled={actionType == 'check'} onChange={(e,val) => { inputChange(val, 'month') }} placeholder="请选择统计月份" />
              )}
            </FormItem>
          </Col>
        </Row>
        <div style={{position: 'absolute',right:'3%',top:'260px'}}><a onClick={e => updateCancel()} href="javascript:void(0);">口径说明</a></div>
      </CollapsiblePanels>
      <div style={{overflowY:'scroll',maxHeight:'564px'}}>
        <Table rowKey={(item, index) => {
                    return index
         }} columns={columns} dataSource={query.Corecompet} pagination={false}/>
      </div>
      <Modal
        width='655px'
        visible={visible}
        destroyOnClose={true}
        onCancel={() => { updateCancel() }}
        footer={null}
      >
        <div style={{padding:'0 60px',color:'#333'}}>
            <div style={{marginBottom:'20px'}}>
              <div>1、业态分类:</div>
              <div>①高层：高层、小高层、超高层;</div>
              <div>②洋房：洋房；</div>
              <div>③叠墅：叠拼别墅；</div>
              <div>④别墅：独立别墅、双拼别墅、联排别墅；</div>
            </div>
            <div>
              <div>2、价格取值：</div>
              <div>①我司项目成交均价：慧销售系统认购均价</div>
              <div>【如：高层成交均价=当月高层类业态总认购金额 / 总认购面积】</div>
              <div>②我司项目成交金额：慧销售认购金额</div>
              <div>【如：高层成交金额=当月高层类业态总认购金】</div>
            </div>
        </div>
      </Modal>
    </div>
  )
}

// 连接视图(view)和模型(model)
export default connect(mapStateToProps)(Form.create()(kernelGoodsDetailView))
